package com.yiren.manager.ctrl.elder;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.dom4j.swing.LeafTreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.FavoriteSet;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrBaseServiceCost;
import com.yiren.entity.YrBeHospitalFee;
import com.yiren.entity.YrBeHospitalPledge;
import com.yiren.entity.YrBed;
import com.yiren.entity.YrBuilding;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderBeHospital;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrElderWallet;
import com.yiren.entity.YrElderWalletRechargeRecord;
import com.yiren.entity.YrFloor;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrMealCardRechargeRecord;
import com.yiren.entity.YrNursingCost;
import com.yiren.entity.YrPaper;
import com.yiren.entity.YrPaperRecord;
import com.yiren.entity.YrRoom;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrSubjectRoom;
import com.yiren.entity.YrUserRfidCard;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrUserVipCardRecord;
import com.yiren.entity.YrUserVipCardRent;
import com.yiren.manager.form.base.YrElderInfoForm;
import com.yiren.manager.form.beds.YrBedForm;
import com.yiren.manager.form.beds.YrBuildingForm;
import com.yiren.manager.form.beds.YrFloorForm;
import com.yiren.manager.form.beds.YrRoomForm;
import com.yiren.manager.form.department.YrSubjectRoomForm;
import com.yiren.manager.form.elder.YrBeHospitalFeeForm;
import com.yiren.manager.form.elder.YrElderBeHospitalForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrElderWalletForm;
import com.yiren.manager.form.pension.YrBaseServiceCostForm;
import com.yiren.manager.form.pension.YrNursingCostForm;
import com.yiren.manager.form.vip.YrUserVipCardForm;
import com.yiren.manager.form.vip.YrUserVipCardRecordForm;
import com.yiren.manager.form.vip.YrUserVipCardRentForm;
import com.yiren.manager.service.iface.base.YrUserRfidCardService;
import com.yiren.manager.service.iface.beds.YrBedService;
import com.yiren.manager.service.iface.beds.YrBuildingService;
import com.yiren.manager.service.iface.beds.YrFloorService;
import com.yiren.manager.service.iface.beds.YrRoomService;
import com.yiren.manager.service.iface.cost.YrPaperService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.department.YrSubjectRoomService;
import com.yiren.manager.service.iface.elder.YrBeHospitalFeeService;
import com.yiren.manager.service.iface.elder.YrElderBeHospitalService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.service.iface.elder.YrElderWalletService;
import com.yiren.manager.service.iface.messhall.YrMealCardService;
import com.yiren.manager.service.iface.pension.YrBaseServiceCostService;
import com.yiren.manager.service.iface.pension.YrNursingCostService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRecordService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRentService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;
import com.yiren.manager.task.DateUtil;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("beHospitalFees")
@Controller
public class YrBeHospitalFeeController extends YrElderBaseController<YrBeHospitalFeeForm, YrBeHospitalFee> {

	@Autowired
	private YrBeHospitalFeeService selfService;

	@Autowired
	private YrElderBeHospitalService elderBeHospitalService;

	@Autowired
	private YrElderService elderService;

	@Autowired
	private YrSubjectRoomService subjectRoomService;

	@Autowired
	private YrUserVipCardService userVipCardService;

	@Autowired
	private YrBuildingService buildingService;

	@Autowired
	private YrFloorService floorService;

	@Autowired
	private YrRoomService roomService;

	@Autowired
	private YrBedService bedService;

	@Autowired
	private YrNursingCostService nursingCostService;

	@Autowired
	private YrBaseServiceCostService baseServiceCostService;

	@Autowired
	private YrUserRfidCardService userRfidCardService;

	@Autowired
	private YrElderWalletService elderWalletService;

	@Autowired
	private YrMealCardService mealCardService;

	@Autowired
	private YrStaffInfoService staffInfoService;

	@Autowired
	private YrUserVipCardRentService userVipCardRentService;

	@Autowired
	private YrUserVipCardRecordService userVipCardRecordService;

	@Autowired
	private YrPaperService paperService;

	@RequestMapping("findElderInfo")
	@ResponseBody
	public HTTPResult<YrElderInfoForm> findElderInfo(String searchVal) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrElderInfoForm> result = new HTTPResult<YrElderInfoForm>();
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere,
				new Object[] { searchVal, searchVal });
		if (qrElder.getTotalRecord() == 0) {
			throwExp("未查到相关资料");
		}

		List<YrElderInfoForm> formList = new ArrayList<YrElderInfoForm>();

		for (YrElder elder : qrElder.getResultList()) {
			formList.add(findDetail(elder, null));
		}

		result.setData(formList);

		return result;
	}

	@RequestMapping("findElderInfoByType")
	@ResponseBody
	public HTTPResult<YrElderInfoForm> findElderInfoByType(String searchVal, Integer elderType, String beHospitalId)
			throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		HTTPResult<YrElderInfoForm> result = new HTTPResult<YrElderInfoForm>();

		List<YrElderInfoForm> formList = new ArrayList<YrElderInfoForm>();
		if (beHospitalId != null) {
			formList.add(findDetail(null, beHospitalId));
		} else {
			String sqlWhere = "(name=?1 OR card_id=?2) AND elder_type=?3";
			QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere,
					new Object[] { searchVal, searchVal, elderType });
			if (qrElder.getTotalRecord() == 0) {
				throwExp("未查到相关资料");
			}
			for (YrElder elder : qrElder.getResultList()) {
				if (elder.getElderType() == 2) {// 如果是院外
					YrElderInfoForm elderInfoForm = new YrElderInfoForm();
					elderInfoForm.setElder(ObjectUtils.objectToObject(elder, YrElderForm.class));
					formList.add(elderInfoForm);
				} else {
					sqlWhere = "elder_id=?1 AND be_status<>2";
					QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
							sqlWhere, new Object[] { elder.getElderId() });
					if (qrElderBeHospital.getResultList().isEmpty()) {
						continue;
					}
					formList.add(findDetail(elder, null));
				}
			}
		}
		result.setData(formList);

		return result;
	}

	@RequestMapping("findElderInfoByElderId")
	@ResponseBody
	private HTTPResult<YrElderInfoForm> findById(String elderId) throws Exception {
		HTTPResult<YrElderInfoForm> result = new HTTPResult<YrElderInfoForm>();

		YrElder elder = elderService.findOne(elderId);
		if (null == elder) {
			throwExp("未查到相关资料");
		}
		List<YrElderInfoForm> formList = new ArrayList<YrElderInfoForm>();
		YrElderInfoForm form = findDetail(elder, null);

		formList.add(form);
		result.setData(formList);

		return result;
	}

	private YrElderInfoForm findDetail(YrElder elder, String beHospitalId) throws MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		YrElderBeHospital elderBeHospital = null;
		if (elder == null) {
			elderBeHospital = elderBeHospitalService.findOne(beHospitalId);
			if (null == elderBeHospital) {
				throwExp("查询不到相关老者住院登记信息");
			}
			elder = elderService.findOne(elderBeHospital.getElderId());
			if (null == elder) {
				throwExp("查询不到老者相关信息");
			}
		} else {
			String sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { elder.getElderId() });
			if (qrElderBeHospital.getResultList().isEmpty()) {
				throwExp("查询不到相关老者住院登记信息或已经出院");
			}
			elderBeHospital = qrElderBeHospital.getResultList().get(0);
		}
		YrElderInfoForm elderInfoForm = new YrElderInfoForm();
		YrSubjectRoom subjectRoom = subjectRoomService.findOne(elderBeHospital.getSubjectRoomId());
		if (null == subjectRoom) {
			throwExp("查询不到老者所在科室信息");
		}
		YrUserVipCard userVipCard = null;
		if (elderBeHospital.getHouseTypeType() == 1) {
			userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
		}
		YrBuilding building = buildingService.findOne(elderBeHospital.getBuildingId());
		if (null == building) {
			throwExp("老者所在楼房不存在");
		}
		YrFloor floor = floorService.findOne(elderBeHospital.getFloorId());
		if (null == floor) {
			throwExp("老者所在楼层不存在");
		}
		YrRoom room = roomService.findOne(elderBeHospital.getRoomId());
		if (null == floor) {
			throwExp("老者所在房间不存在");
		}
		YrBed bed = bedService.findOne(elderBeHospital.getBedId());
		if (null == bed) {
			throwExp("老者所在床位不存在");
		}
		YrNursingCost nursingCost = nursingCostService.findOne(elderBeHospital.getNursingCostId());
		if (null == nursingCost) {
			throwExp("老者护理费信息不存在");
		}
		YrBaseServiceCost baseServiceCost = baseServiceCostService.findOne(elderBeHospital.getBaseServiceCostId());
		if (null == baseServiceCost) {
			throwExp("老者护基础服务费信息不存在");
		}

		String sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1 AND status=0";

		QueryResult<YrStaffInfo> qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere,
				new Object[] { elderBeHospital.getSubjectRoomId() });
		if (qrStaffInfo.getTotalRecord() > 0) {
			elderInfoForm.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
		}
		YrElderWallet elderWallet = null;
		sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { elder.getElderId() });
		if (qrElderWallet.getTotalRecord() > 0) {
			elderWallet = qrElderWallet.getResultList().get(0);
		} else {
			throwExp("查询不到该老者钱包信息");
		}

		elderInfoForm.setHouseTyeType(elderBeHospital.getHouseTypeType());

		elderInfoForm.setSubjectRoom(ObjectUtils.objectToObject(subjectRoom, YrSubjectRoomForm.class));

		if (null != userVipCard) {
			YrUserVipCardForm userVipCardForm = ObjectUtils.objectToObject(userVipCard, YrUserVipCardForm.class);

			if (!StringUtil.isEmpty(userVipCardForm.getCreateId())) {
				YrStaffInfo staffInfo = staffInfoService.findOne(userVipCardForm.getCreateId());
				if (null != staffInfo) {
					userVipCardForm.setCreator(staffInfo.getName());
				}
			}
			if (!StringUtil.isEmpty(userVipCardForm.getUpdateId())) {
				YrStaffInfo staffInfo = staffInfoService.findOne(userVipCardForm.getUpdateId());
				if (null != staffInfo) {
					userVipCardForm.setMender(staffInfo.getName());
				}
			}
			sqlWhere = "user_vip_card_id=?1";
			QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService
					.find(YrUserVipCardRecord.class, sqlWhere, new Object[] { userVipCardForm.getUserVipCardId() });
			if (qrUserVipCardRecord.getTotalRecord() > 0) {
				userVipCardForm.setUserVipCardRecordForm(ObjectUtils
						.objectToObject(qrUserVipCardRecord.getResultList().get(0), YrUserVipCardRecordForm.class));
			}
			QueryResult<YrUserVipCardRent> qrUserVipCardRent = userVipCardRentService.find(YrUserVipCardRent.class,
					sqlWhere, new Object[] { userVipCardForm.getUserVipCardId() });
			List<YrUserVipCardRentForm> userVipCardRentForms = new ArrayList<YrUserVipCardRentForm>();
			for (YrUserVipCardRent userVipCardRent : qrUserVipCardRent.getResultList()) {
				userVipCardRentForms.add(ObjectUtils.objectToObject(userVipCardRent, YrUserVipCardRentForm.class));
			}
			userVipCardForm.setUserVipCardRentForms(userVipCardRentForms);

			elderInfoForm.setUserVipCardForm(userVipCardForm);
		}

		YrElderBeHospitalForm elderBeHospitalForm = ObjectUtils.objectToObject(elderBeHospital,
				YrElderBeHospitalForm.class);
		sqlWhere = "subject_room_id=?1 AND manager_of_subject_room=1 AND status=0";

		qrStaffInfo = staffInfoService.find(YrStaffInfo.class, sqlWhere,
				new Object[] { elderBeHospital.getSubjectRoomId() });
		if (qrStaffInfo.getTotalRecord() > 0) {
			elderBeHospitalForm.setSubjectRoomManager(qrStaffInfo.getResultList().get(0).getName());
		}

		sqlWhere = "elder_id=?1";
		YrBeHospitalFeeForm beHospitalFeeForm = null;
		QueryResult<YrBeHospitalFee> qrBeHospitalFee = selfService.find(YrBeHospitalFee.class, sqlWhere,
				new Object[] { elderBeHospital.getElderId() });
		if (qrBeHospitalFee.getTotalRecord() > 0) {
			YrBeHospitalFee beHospitalFee = qrBeHospitalFee.getResultList().get(0);
			beHospitalFeeForm = ObjectUtils.objectToObject(beHospitalFee, YrBeHospitalFeeForm.class);
		}

		elderInfoForm.setBuilding(ObjectUtils.objectToObject(building, YrBuildingForm.class));
		elderInfoForm.setFloor(ObjectUtils.objectToObject(floor, YrFloorForm.class));
		elderInfoForm.setRoom(ObjectUtils.objectToObject(room, YrRoomForm.class));
		elderInfoForm.setBed(ObjectUtils.objectToObject(bed, YrBedForm.class));
		elderInfoForm.setNursingCost(ObjectUtils.objectToObject(nursingCost, YrNursingCostForm.class));
		elderInfoForm.setBaseServiceCost(ObjectUtils.objectToObject(baseServiceCost, YrBaseServiceCostForm.class));
		elderInfoForm.setElderBeHospitalForm(elderBeHospitalForm);
		elderInfoForm.setElderWalletForm(ObjectUtils.objectToObject(elderWallet, YrElderWalletForm.class));
		elderInfoForm.setBeHospitalFeeForm(beHospitalFeeForm);

		elderInfoForm.setElder(ObjectUtils.objectToObject(elder, YrElderForm.class));

		return elderInfoForm;
	}

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrBeHospitalFeeForm> save(String data)
			throws SwallowException, MyException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrBeHospitalFeeForm> result = new HTTPResult<YrBeHospitalFeeForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrBeHospitalFeeForm form = tool.mapper("beHospitalFees", YrBeHospitalFeeForm.class);
		if (null == form) {
			throwExp("param.error");
		}

		Date now = new Date();
		if (null == form.getBeHospitalFeesId() || form.getBeHospitalFeesId().isEmpty()) {
			form.setBeHospitalFeesId(UUIDGenerator.getUUID());
			form.setCreateTime(now);
		}

		String elderId = form.getElderId();

		String sqlWhere = "elder_id=?1 AND be_status=0";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { elderId });
		if (qrElderBeHospital.getTotalRecord() == 0) {
			throwExp("查询不到该老者的住院信息");
		}

		sqlWhere = "elder_id=?1 AND be_hospital_id=?2";

		QueryResult<YrBeHospitalFee> qrBeHospitalFee = selfService.find(YrBeHospitalFee.class, sqlWhere,
				new Object[] { form.getElderId(), qrElderBeHospital.getResultList().get(0).getBeHospitalId() });
		if (qrBeHospitalFee.getTotalRecord() > 0) {
			throwExp("该老者已办理过入院缴费手续，请勿重复办理");
		}
		YrElder elder = elderService.findOne(elderId);
		if (null == elder) {
			throwExp("查询不到相关老者信息");
		}

		YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
		elderBeHospital.setPrePayDate(now);

		YrUserVipCard userVipCard = null;
		if (elderBeHospital.getHouseTypeType() == 1) {// 如果是vip卡入住
			userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
			if (null == userVipCard) {
				throwExp("未查到用户vip卡信息");
			}
			userVipCard.setPrePayDate(now);
		}

		List<YrElderPayRecord> elderPayRecords = new ArrayList<YrElderPayRecord>();

		// 增加一条床位费记录
		// elderPayRecords.add(costElderPayRecord("床位费", elder, 4,
		// elderBeHospital.getBeHospitalId(),
		// form.getBedCost(),1,0,form.getCreateId()));

		// YrBaseServiceCost baseServiceCost =
		// baseServiceCostService.findOne(elderBeHospital.getBaseServiceCostId());
		// 基础服务费
		// elderPayRecords.add(costElderPayRecord(baseServiceCost.getServiceName(),
		// elder, 1,
		// elderBeHospital.getBeHospitalId(),
		// form.getBaseServiceCost(),1,0,form.getCreateId()));

		// 预缴水费
		elderPayRecords.add(costElderPayRecord(elderBeHospital.getBeHospitalId(), "预缴水费", elder, 5,
				form.getBeHospitalFeesId(), form.getWaterPay(), 1, 0, form.getCreateId(), 1));
		// 预缴电费
		elderPayRecords.add(costElderPayRecord(elderBeHospital.getBeHospitalId(), "预缴电费", elder, 6,
				form.getBeHospitalFeesId(), form.getElectricityPay(), 1, 0, form.getCreateId(), 1));
		// 预缴热水费
		elderPayRecords.add(costElderPayRecord(elderBeHospital.getBeHospitalId(), "预缴热水费", elder, 7,
				form.getBeHospitalFeesId(), form.getHotWaterPay(), 1, 0, form.getCreateId(), 1));

		// YrNursingCost nursingCost =
		// nursingCostService.findOne(elderBeHospital.getNursingCostId());
		// 护理费
		// elderPayRecords.add(costElderPayRecord(nursingCost.getNursingCostName(),
		// elder, 2,
		// elderBeHospital.getBeHospitalId(),
		// form.getNursingCost(),1,0,form.getCreateId()));

		sqlWhere = "user_relation_id=?1";
		QueryResult<YrUserRfidCard> qrUserRfidCard = userRfidCardService.find(YrUserRfidCard.class, sqlWhere,
				new Object[] { elder.getElderId() });

		YrUserRfidCard userRfidCard = null;
		if (qrUserRfidCard.getTotalRecord() > 0) {
			userRfidCard = qrUserRfidCard.getResultList().get(0);
		}
		sqlWhere = "elder_id=?1";
		QueryResult<YrElderWallet> qrElderWallet = elderWalletService.find(YrElderWallet.class, sqlWhere,
				new Object[] { elder.getElderId() });

		YrElderWallet elderWallet = null;
		// 钱包充值
		if (qrElderWallet.getTotalRecord() == 0) {
			throwExp("该老者尚无钱包");
		}
		elderWallet = qrElderWallet.getResultList().get(0);
		elderWallet.setUserRfidCardId(userRfidCard == null ? null : userRfidCard.getUserRfidCardId());

		// 新增一条钱包充值记录
		YrElderWalletRechargeRecord elderWalletRechargeRecord = null;
		if(form.getElderWalletPay()>0){
			elderWallet.setWalletBalance(elderWallet.getWalletBalance() + form.getElderWalletPay());
			elderWalletRechargeRecord = new YrElderWalletRechargeRecord();
			elderWalletRechargeRecord.setElderWalletRechargeRecordId(UUIDGenerator.getUUID());
			elderWalletRechargeRecord.setElderId(elderWallet.getElderId());
			elderWalletRechargeRecord.setElderName(elderWallet.getElderName());
			elderWalletRechargeRecord.setElderCarId(elderWallet.getElderCardId());
			elderWalletRechargeRecord.setRechargeMoney(form.getElderWalletPay());
			elderWalletRechargeRecord.setRechargeDate(now);
			elderWalletRechargeRecord.setCreateTime(now);
			elderWalletRechargeRecord.setCreateId(form.getCreateId());
			elderWalletRechargeRecord.setBeHospitalId(elderBeHospital.getBeHospitalId());
		}

		sqlWhere = "card_person_id=?1";
		QueryResult<YrMealCard> qrMealCard = mealCardService.find(YrMealCard.class, sqlWhere,
				new Object[] { elder.getElderId() });

		YrMealCard mealCard = null;
		if (qrMealCard.getTotalRecord() == 0) {
			throwExp("该老者尚无饭卡");
		}
		mealCard = qrMealCard.getResultList().get(0);

		// 新增一条饭卡充值记录
		YrMealCardRechargeRecord mealCardRechargeRecord = null;
		if (form.getMealCardPay() > 0) {
			mealCard.setBalance(mealCard.getBalance() + form.getMealCardPay());
			mealCardRechargeRecord = new YrMealCardRechargeRecord();
			mealCardRechargeRecord.setMealCardRechargeRecordId(UUIDGenerator.getUUID());
			mealCardRechargeRecord.setCardPersonId(mealCard.getCardPersonId());
			mealCardRechargeRecord.setCardPersonName(mealCard.getCardPersonName());
			mealCardRechargeRecord.setCardCardId(mealCard.getCardCardId());
			mealCardRechargeRecord.setCardType(mealCard.getCardType());
			mealCardRechargeRecord.setUserRfidCardId(mealCard.getUserRfidCardId());
			mealCardRechargeRecord.setPersonType(mealCard.getPersonType());
			mealCardRechargeRecord.setRechargeMoney(form.getMealCardPay());
			mealCardRechargeRecord.setRechargeDate(now);
			mealCardRechargeRecord.setCreateId(form.getCreateId());
			mealCardRechargeRecord.setCreateTime(now);
		}
		YrBeHospitalPledge hospitalPledge = new YrBeHospitalPledge();
		hospitalPledge.setBeHospitalPledgeId(UUIDGenerator.getUUID());
		hospitalPledge.setElderId(elder.getElderId());
		hospitalPledge.setElderName(elder.getName());
		hospitalPledge.setElderCardId(elder.getCardId());
		hospitalPledge.setPledge(form.getPledgePay());
		hospitalPledge.setSubjectRoomId(elderBeHospital.getSubjectRoomId());
		hospitalPledge.setHandleId(form.getCreateId() == null ? "-1" : form.getCreateId());
		hospitalPledge.setCreateTime(new Date());
		hospitalPledge.setCreateId(form.getCreateId());
		hospitalPledge.setPayTime(new Date());
		hospitalPledge.setStatus(0);
		hospitalPledge.setBeHospitalId(elderBeHospital.getBeHospitalId());
		if (null != form.getCreateId()) {
			YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
			hospitalPledge.setHandleName(staffInfo == null ? "" : staffInfo.getName());
		}

		FavoriteSet favoriteSet = new FavoriteSet();

		YrBeHospitalFee entity = ObjectUtils.objectToObject(form, YrBeHospitalFee.class);

		entity.setBeHospitalId(elderBeHospital.getBeHospitalId());

		// 获取票据号码
		sqlWhere = "staff_id=?1 AND paper_type=2";
		QueryResult<YrPaper> qrPaper = paperService.find(YrPaper.class, sqlWhere, new Object[] { form.getCreateId() });

		if (qrPaper.getResultList().isEmpty()) {
			throwExp("暂无该类型的票据号，请先设置");
		}

		YrPaper paper = qrPaper.getResultList().get(0);

		/**
		 * 押金的打印记录
		 */
		YrPaperRecord pledePaperRecord = null;
		if (form.getPledgePay() > 0) {
			pledePaperRecord = costPaperRecord(paper, elderBeHospital.getBeHospitalId(), form.getCreateId(),
					form.getPledgePay(), 2);
			pledePaperRecord.setRelationId(elderBeHospital.getBeHospitalId() + "-beHospitalPlede");

			paper.setUseNum(toNumberStr(paper.getUseNum()));
		}

		/**
		 * 预交款打印记录
		 */
		YrPaperRecord payPaperRecord = null;
		
		Float prePay = (form.getElderWalletPay()==null?0:form.getElderWalletPay())+
				(form.getWaterPay()==null?0:form.getWaterPay())+ 
						(form.getElectricityPay()==null?0:form.getElectricityPay())+ 
								(form.getHotWaterPay()==null?0:form.getHotWaterPay());
		
		if (prePay > 0) {
			payPaperRecord = costPaperRecord(paper, elderBeHospital.getBeHospitalId(), form.getCreateId(),
					prePay, 2);
			payPaperRecord.setRelationId(elderBeHospital.getBeHospitalId() + "-prePay");
			paper.setUseNum(toNumberStr(paper.getUseNum()));
		}

		favoriteSet.putFavorite("beHospitalFee", entity);
		favoriteSet.putFavorite("elderWallet", elderWallet);
		favoriteSet.putFavorite("mealCard", mealCard);
		favoriteSet.putFavorite("beHospitalPledge", hospitalPledge);
		favoriteSet.putFavorite("elderBeHospital", elderBeHospital);
		favoriteSet.putFavorite("userVipCard", userVipCard);
		// 缴费记录列表
		favoriteSet.putFavorite("elderPayRecords", elderPayRecords);
		// 钱包充值记录
		favoriteSet.putFavorite("mealCardRechargeRecord", mealCardRechargeRecord);
		// 饭卡充值记录
		favoriteSet.putFavorite("elderWalletRechargeRecord", elderWalletRechargeRecord);
		favoriteSet.putFavorite("pledePaperRecord", pledePaperRecord);
		favoriteSet.putFavorite("payPaperRecord", payPaperRecord);
		favoriteSet.putFavorite("paper", paper);

		selfService.addByFavoriteSet(favoriteSet);

		List<YrBeHospitalFeeForm> formList = new ArrayList<YrBeHospitalFeeForm>();
		formList.add(form);
		result.setData(formList);
		return result;
	}

	@RequestMapping("updateFees")
	@ResponseBody
	public HTTPResult<YrElderInfoForm> updateFees(String data) throws MyException, SwallowException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HTTPResult<YrElderInfoForm> result = new HTTPResult<YrElderInfoForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrBeHospitalFeeForm beHospitalFeesForm = tool.mapper("beHospitalFees", YrBeHospitalFeeForm.class);
		YrElderBeHospitalForm elderBeHospitalForm = tool.mapper("elderBeHospital", YrElderBeHospitalForm.class);

		if (null == beHospitalFeesForm) {
			throwExp("param.error");
		}

		String elderId = beHospitalFeesForm.getElderId();

		String sqlWhere = "elder_id=?1 AND be_status<>2";
		QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
				sqlWhere, new Object[] { elderId });

		if (qrElderBeHospital.getTotalRecord() == 0) {
			throwExp("查询不到该老者的住院信息");
		}

		YrElder elder = elderService.findOne(elderId);
		if (null == elder) {
			throwExp("查询不到相关老者信息");
		}

		YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);

		YrUserVipCard userVipCard = null;
		if (elderBeHospital.getHouseTypeType() == 1) {// 如果是vip卡入住
			userVipCard = userVipCardService.findOne(elderBeHospital.getUserVipCardId());
			if (null == userVipCard) {
				throwExp("未查到用户vip卡信息");
			}
		}
		beHospitalFeesForm.setUpdateTime(new Date());
		YrBeHospitalFee entity = ObjectUtils.objectToObject(beHospitalFeesForm, YrBeHospitalFee.class);

		elderBeHospitalForm.setUpdateTime(new Date());
		YrElderBeHospital elderBeHospitalEntity = ObjectUtils.objectToObject(elderBeHospitalForm,
				YrElderBeHospital.class);

		selfService.save(entity);
		elderBeHospitalService.save(elderBeHospitalEntity);

		YrElderInfoForm elderInfoForm = new YrElderInfoForm();
		elderInfoForm.setElderBeHospitalForm(elderBeHospitalForm);
		elderInfoForm.setBeHospitalFeeForm(beHospitalFeesForm);

		List<YrElderInfoForm> formList = new ArrayList<YrElderInfoForm>();
		formList.add(elderInfoForm);

		result.setData(formList);
		return result;

	}

	/**
	 * 增加住院时长
	 * 
	 * @param elderId
	 * @param monthNum
	 * @return
	 * @throws MyException
	 */
	@RequestMapping("addBeTime")
	@ResponseBody
	public HTTPResult<YrBeHospitalFeeForm> addBeTime(String elderId, Integer monthNum) throws MyException {
		HTTPResult<YrBeHospitalFeeForm> result = new HTTPResult<YrBeHospitalFeeForm>();
		String sqlWhere = "elder_id=?1";
		QueryResult<YrBeHospitalFee> qr = selfService.find(YrBeHospitalFee.class, sqlWhere, new Object[] { elderId });
		if (qr.getTotalRecord() == 0) {
			throwExp("该老者未办理入院缴费，请先办理");
		}
		YrBeHospitalFee entity = qr.getResultList().get(0);
		Date outTime = entity.getOutHospitalTime();

		// SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd,hh:mm:ss");
		Calendar c = Calendar.getInstance();
		c.setTime(outTime);
		c.add(Calendar.DAY_OF_MONTH, 2);
		entity.setOutHospitalTime(c.getTime());

		selfService.save(entity);
		return result;
	}

	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrBeHospitalFeeForm> find(String searchVal) throws Exception {
		HTTPResult<YrBeHospitalFeeForm> result = new HTTPResult<YrBeHospitalFeeForm>();
		String sqlWhere = "name=?1 OR card_id=?2 AND elder_type=1";
		QueryResult<YrElder> qr = elderService.find(YrElder.class, sqlWhere, new Object[] { searchVal, searchVal });

		List<YrBeHospitalFeeForm> formList = new ArrayList<YrBeHospitalFeeForm>();
		if (qr.getTotalRecord() > 0) {
			YrElder elder = qr.getResultList().get(0);
			sqlWhere = "elder_id=?1";
			QueryResult<YrBeHospitalFee> qrBeHospitalFee = selfService.find(YrBeHospitalFee.class, sqlWhere,
					new Object[] { elder.getElderId() });
			YrBeHospitalFeeForm beHospitalFeeForm = new YrBeHospitalFeeForm();
			if (qrBeHospitalFee.getTotalRecord() > 0) {
				beHospitalFeeForm = ObjectUtils.objectToObject(qrBeHospitalFee.getResultList().get(0),
						YrBeHospitalFeeForm.class);
			}
			beHospitalFeeForm.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			formList.add(beHospitalFeeForm);
		}
		result.setData(formList);
		return result;
	}

	/**
	 * 到期提醒
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("expireRemind")
	@ResponseBody
	public HTTPResult<YrBeHospitalFeeForm> expireRemind() throws Exception {
		HTTPResult<YrBeHospitalFeeForm> result = new HTTPResult<YrBeHospitalFeeForm>();
		String sqlWhere = "TO_DAYS(out_hospital_time)-TO_DAYS(NOW())<15";

		QueryResult<YrBeHospitalFee> qr = selfService.find(YrBeHospitalFee.class, sqlWhere, new Object[] {});

		List<YrBeHospitalFeeForm> formList = new ArrayList<YrBeHospitalFeeForm>();
		for (YrBeHospitalFee entity : qr.getResultList()) {
			YrBeHospitalFeeForm form = toForm(entity);
			YrElder elder = elderService.findOne(entity.getElderId());
			if (elder != null) {
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			Date date = new Date();
			form.setExpireDays(DateUtil.daysOfTwo(entity.getOutHospitalTime(), date));
			formList.add(form);
		}

		return result;
	}

	@RequestMapping("findByDay")
	@ResponseBody
	public HTTPResult<YrBeHospitalFeeForm> findByDay(String day, String searchVal) throws Exception {
		HTTPResult<YrBeHospitalFeeForm> result = new HTTPResult<YrBeHospitalFeeForm>();

		String sqlWhere = "SELECT a from YrBeHospitalFee a , YrElder b WHERE b.elderId=a.elderId AND "
				+ "DATE_FORMAT(a.createTime,'%Y-%m-%d')=?1 AND (b.name=?2 OR b.cardId=?2) AND b.elderType=1";
		List<YrBeHospitalFee> beHospitalFees = selfService.findByJPQL(sqlWhere, new Object[] { day, searchVal });

		List<YrBeHospitalFeeForm> formList = new ArrayList<YrBeHospitalFeeForm>();
		for (YrBeHospitalFee entity : beHospitalFees) {
			YrBeHospitalFeeForm form = toForm(entity);
			YrElder elder = elderService.findOne(entity.getElderId());
			if (elder != null) {
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			sqlWhere = "elder_id=?1 AND be_status<>2";
			QueryResult<YrElderBeHospital> qrElderBeHospital = elderBeHospitalService.find(YrElderBeHospital.class,
					sqlWhere, new Object[] { form.getElderId() });
			if (!qrElderBeHospital.getResultList().isEmpty()) {
				YrElderBeHospital elderBeHospital = qrElderBeHospital.getResultList().get(0);
				form.setElderBeHospitalForm(ObjectUtils.objectToObject(elderBeHospital, YrElderBeHospitalForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}

	@Override
	public YrBeHospitalFeeForm toForm(YrBeHospitalFee e) throws Exception {
		YrBeHospitalFeeForm form = ObjectUtils.objectToObject(e, YrBeHospitalFeeForm.class);
		return form;
	}

	@Override
	public YrBeHospitalFee toEntity(YrBeHospitalFeeForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
